import logging

from django.http import JsonResponse

from comment.comviews import err_response
from utils.pageutils import paging_index


def add_filter(sql, body_params, filter_params, **filter_sql):
    """
    添加过滤查询
    :param sql: sql语句
    :param body_params:请求体参数
    :param filter_params: 过滤参数
    :param filter_sql: 过滤sql语句
    :return:
    """
    if not " where " in sql:
        sql += " where 1=1 "
    for param in filter_params:
        if filter_sql.get(param) is not None and body_params.get(param) is not None:
            sql += " and " + filter_sql.get(param)
    logging.info("add_filter:{}".format(sql))
    return sql


def add_filter_limit(sql, body_params, filter_params, **filter_sql):
    """
    添加过滤查询
    :param sql: sql语句
    :param body_params:请求体参数
    :param filter_params: 过滤参数
    :param filter_sql: 过滤sql语句
    :return:
    """
    if not " where " in sql:
        sql += " where 1=1 "
    for param in filter_params:
        if filter_sql.get(param) is not None and body_params.get(param) is not None:
            sql += " and " + filter_sql.get(param)
    logging.info("add_filter:{}".format(sql))
    if "size" in filter_params and "page" in filter_params:
        add_limit(sql, body_params.get("size"), body_params.get("page"))
    return sql


def add_limit(sql, size, page):
    """
    添加sql分页
    :param sql: sql语句
    :param body_params:请求体参数
    :param filter_params: 过滤参数
    :param filter_sql: 过滤sql语句
    :return:
    """
    if "limit" in sql:
        return err_response(401, "sql中包含limit参数")
    start_index = paging_index(size, page)
    logging.info("add_filter:{}".format(sql))
    sql += " limit {},{}".format(start_index, size)
    return sql
